<!-- eslint-disable no-console -->
<template>
  <CommonPage>
    <template #action>
      <NButton @click="addOrUpdateImport()">
        导入或新增
      </NButton>
      <NButton @click="goodsExport({})">
        下载物料
      </NButton>
      <NButton @click="toGoodsDetails({})">
        新增商品
      </NButton>
    </template>

    <MeCrud ref="$table" v-model:query-items="queryItems" :scroll-x="1200" :columns="columns" :get-data="api.read">
      <MeQueryItem label="商品名">
        <n-input v-model:value="queryItems.goodsName" type="text" placeholder="请输入用户名" clearable />
      </MeQueryItem>
      <MeQueryItem label="商品标签">
        <n-select
          v-model:value="queryItems.goodsTagId" label-field="title" value-field="id"
          :options="goodsTagOptions"
        />
      </MeQueryItem>
      <MeQueryItem label="商品分类">
        <n-select
          v-model:value="queryItems.goodsTypeId" :options="goodsTypeOptions" label-field="name" value-field="id"
          clearable remote
        />
      </MeQueryItem>
    </MeCrud>
  </CommonPage>
  <!-- -----------------上传excel------------------------ -->
  <n-drawer v-model:show="active" height="302" placement="top">
    <n-drawer-content title="上传物料" header-class="header-drawer">
      <n-upload directory-dnd multiple :custom-request="customRequest" :max="5">
        <n-upload-dragger>
          <div style="margin-bottom: 12px">
            <n-icon size="48" :depth="3">
              <ArchiveIcon />
            </n-icon>
          </div>
          <n-text style="font-size: 16px">
            点击或者拖动文件到该区域来上传
          </n-text>
          <n-p depth="3" style="margin: 8px 0 0 0">
            请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
          </n-p>
        </n-upload-dragger>
      </n-upload>
    </n-drawer-content>
  </n-drawer>
  <!-- -----------------商品标签------------------------ -->
  <MeModal ref="$modalTag">
    <n-transfer v-model:value="goodsTagValue" :options="goodsTagOptions" />
  </MeModal>
  <!-- -----------------商品标签end------------------------ -->
</template>

<script setup>
import apiGlobal from '@/api'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useModal } from '@/composables'
import { request } from '@/utils'
import { NAvatar, NButton, NSwitch, NTag } from 'naive-ui'
import api from './api'

defineOptions({ name: 'GoodsMgt' })
const router = useRouter()
const $table = ref(null)
const [$modalTag, modalTagLoading] = useModal()
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
const goodsTypeOptions = ref([
  {
    label: '早点',
    value: '1762092977440391173',
  },
  {
    label: '商品类型1',
    value: '1762092977440391174',
  },
])

const columns = [
  { title: '商品名', key: 'goodsName', width: 150, ellipsis: { tooltip: true } },
  { title: '商品分类', key: 'goodsTypeName', width: 150, ellipsis: { tooltip: true } },
  {
    title: '标签',
    key: 'tags',
    width: 200,
    ellipsis: { tooltip: true },
    render: ({ tags }) => {
      if (tags?.length) {
        return tags.map((item, index) =>
          h(
            NTag,
            { type: 'success', style: index > 0 ? 'margin-left: 8px;' : '' },
            { default: () => item.title },
          ),
        )
      }
      return '暂无标签'
    },
  },
  { title: '价格', key: 'price', width: 150, ellipsis: { tooltip: true } },
  {
    title: '图片',
    key: 'goodsPics',
    width: 80,
    render: (_row) => {
      return _row.goodsPics.split(',').map((item) => {
        return h(NAvatar, {
          size: 'medium',
          src: item,
        })
      })
    },
  },
  {
    title: '状态',
    key: 'enableStatusName',
    width: 150,
    ellipsis: { tooltip: true },
    render: row =>
      h(NSwitch, {
        'value': row.enableStatus === 1,
        'onUpdate:value': val => switchGoondsStatus(val, row),
      }, {
        checked: () => h('div', '启用'),
        unchecked: () => h('div', '禁用'),
      }),
  },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    fixed: 'right',
    align: 'center',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => toGoodsDetails(row),
          },
          {
            default: () => '详情',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => goodsExport({ goodsId: row.id }),
          },
          {
            default: () => '导出',
            icon: () => h('i', { class: 'i-radix-icons:reset text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            onClick: () => openGoodsTagModel(row),
          },
          {
            default: () => '打标签',
            icon: () => h('i', { class: 'i-radix-icons:reset text-14' }),
          },
        ),
      ]
    },
  },
]
const goodsTagOptions = ref([])
onMounted(async () => {
  $table.value?.handleSearch()
  goodsTagOptions.value = await apiGlobal.getGoodsTagOptions({})
  goodsTypeOptions.value = await api.goodsTypeList()
})
// --------------------------------商品导出-----------------------------------------------3
function goodsExport(data) {
  request({
    method: 'POST',
    url: '/system/goods/export2',
    data,
    responseType: 'blob', // 告诉axios我们期望得到一个blob对象
  })
    .then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', 'downloaded_file.xlsx') // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      // 清理
      window.URL.revokeObjectURL(url)
      link.remove()
    })
    .catch((error) => {
      console.error('下载失败:', error)
    })
}
// --------------------------------商品导入-----------------------------------------------3
const active = ref(false)
function addOrUpdateImport(_place) {
  active.value = true
}
function customRequest({
  file,
  onFinish,
  onError,
}) {
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('otherField', 'some value')
  request.post('/system/goods/import/temp2', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }).then(() => {
    onFinish()
  }).catch(() => {
    onError()
  })
}
// <!-- -----------------商品标签------------------------ -->
const goodsTagValue = ref()
async function openGoodsTagModel(rowData) {
  await api.goodsTagList()
    .then((res) => {
      goodsTagOptions.value = res.map((item) => {
        return { label: item.title, value: item.id }
      })
      goodsTagValue.value = rowData.tags.map((item) => {
        return item.id
      })
    })
  $modalTag.value?.open({
    title: '设置标签',
    width: '600px',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      modalTagLoading.value = true
      const goodsTagRelList = goodsTagValue.value.map((item) => {
        return { goodsId: rowData.id, tagId: item }
      })
      await api.goodsBindTags(rowData.id, goodsTagRelList)
      modalTagLoading.value = false
      $table.value?.handleSearch()
    },
    onCancel(message) {
      $message.info(message ?? '已取消')
    },
  })
}
// --------------------------------商品详情-----------------------------------------------
function toGoodsDetails(row) {
  router.push({ path: `/goods/model/${row.id}`, query: { goodsId: row.id } })
}
// 启用或禁用商品状态
async function switchGoondsStatus(isOk, row) {
  // 构造更新参数
  const param = {
    id: row.id,
    enableStatus: isOk ? 1 : 0,
  }
  await api.goodsSaveOrUpdate(param)
  $table.value?.handleSearch()
}
</script>

<style>
.header-drawer {
  /* display: flex; */
  justify-content: center !important;
  text-align: center;
}
</style>
